<?php
namespace Xxfaxy\DryBundle\Services;

class Fos
{

    protected $container;

    public function __construct($service_container)
    {
        $this->container = $service_container;
    }

    public function getUser()
    {
        return $this->container->get('security.token_storage')->getToken()->getUser();
    }

    public function getUserInformation($id)
    {
        $crud = $this->container->get('service.crud')->switch2assoc();
        $function = $this->container->get('service.common.function');
        $setting = $function->getSetting();
        $sql = "
        select
        ug.group_id,
        g.roles
        from fos_user_group ug
        left join fos_group g on g.id=ug.group_id
        where ug.user_id={$id}
        ";
        $list = $crud->fetchAll($sql);
        $groups = $roles = $routeList = array();
        foreach($list as $item){
            $groups[] = $item['group_id'];
            $temp = unserialize($item['roles']);
            foreach($temp as $v){
                $roles[] = $v;
            }
        }
        $groupIdString = implode(',', $groups);
        $sql = "select dryRouteName from group_permission where dryGroup in ({$groupIdString})";
        $list = $crud->fetchAll($sql);
        foreach($list as $item){
            $routeList[$item['dryRouteName']] = $item['dryRouteName'];
        }
        $pass = json_decode($setting->all_user_has_permission_route, true);
        $forbid = json_decode($setting->all_user_no_has_permission_route, true);
        $sql = "
        select
        up.*
        from dry_user_permission up
        left join fos_user u on u.username=up.dry_username
        where u.id={$id} and up.dry_status=1
        ";
        $list = $crud->fetchAll($sql);
        foreach($list as $item){
            if($item['dry_own'] == 'yes'){
                $routeList[$item['dry_route']] = $item['dry_route'];
            }
        }
        foreach($pass as $item){
            $routeList[$item] = $item;
        }
        foreach($list as $item){
            if($item['dry_own'] == 'no'){
                if(isset($routeList[$item['dry_route']])){
                    unset($routeList[$item['dry_route']]);
                }
            }
        }
        foreach($forbid as $item){
            if(isset($routeList[$item])){
                unset($routeList[$item]);
            }
        }
        $result = array(
            'group_id_array' => $groups,
            'group_id_string' => $groupIdString,
            'group_array' => $roles,
            'group_string' => implode(',', $roles),
            'is_super_admin' => in_array('ROLE_SUPER_ADMIN', $roles),
            'route_list' => $routeList
        );
        return $result;
    }

    public function hasRole($role)
    {
        $user = $this->getUser();
        $infomation = $this->getUserInformation($user->getId());
        return in_array($role, $infomation['group_array']);
    }

    public function isSuperAdmin()
    {
        return $this->hasRole('ROLE_SUPER_ADMIN');
    }

    /*
    src/Xxfaxy/DryBundle/Services/Listener/CheckPermissionListener.php
    */
    public function checkSecurity($user, $route_name)
    {
        $info = $this->getUserInformation($user->getId());
        $adminPath = $this->container->getParameter('admin_path');
        $request = $this->container->get('request');
        $requestUri = $request->getPathInfo();
        if($info['is_super_admin']){
            return true;
        }
        if(substr($requestUri, 1, strlen($adminPath)) != $adminPath){
            return true;
        }
        if(in_array($route_name, $info['route_list'])){
            return true;
        }
        else{
            return false;
        }
    }

    public function isPasswordValid($username, $password)
    {
        $encoder = $this->container->get('security.password_encoder');
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $user = $em->getRepository('XxfaxyUserBundle:User')->findOneByUsername($username);
        if($user){
            return $encoder->isPasswordValid($user, $password);
        }
        return false;
    }

    public function resetUserPassword($username, $password)
    {
        $encoder = $this->container->get('security.password_encoder');
        $em = $this->container->get('doctrine.orm.default_entity_manager');
        $user = $em->getRepository('XxfaxyUserBundle:User')->findOneByUsername($username);
        if($user){
            $passwordEncode = $encoder->encodePassword($user, $password);
            $user->setPassword($passwordEncode);
            $em->flush();
            return true;
        }
        return false;
    }

}
